package com.ubestkid.kidrhymes.presenter;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;

import com.hisavana.mediation.config.TAdManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.model.Response;
import com.ubestkid.kidrhymes.AppApplication;
import com.ubestkid.kidrhymes.common.interceptor.LoggerInterceptor;

import com.ubestkid.kidrhymes.constant.API;
import com.ubestkid.kidrhymes.constant.Constants;
import com.ubestkid.kidrhymes.net.DResponse;
import com.ubestkid.kidrhymes.net.NormalCallBack;
import com.ubestkid.kidrhymes.net.SSLSocketClient;
import com.ubestkid.kidrhymes.utils.AppUtil;
import com.ubestkid.kidrhymes.utils.JSONUtil;
import com.ubestkid.kidrhymes.utils.LogUtils;
import com.ubestkid.kidrhymes.utils.SafeJsonUtil;
import com.ubestkid.kidrhymes.utils.SharedPreferencesUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;

public class STAdManager {
    static STAdManager instance;

    String originalAppId;

    Context  context;

    OnRecordCallBack onRecordCallBack;

    OnCallBack  onCallBack;

    public static STAdManager getInstance() {
        if (instance == null) {
            instance = new STAdManager();
        }

        return instance;
    }


    public void initSdk(String appId, Application application, boolean isDebug, boolean isTestDevice) {
        context = application.getApplicationContext();
        initNet(application);
        initFileProvider();

        this.originalAppId = appId;
        String versionName = AppUtil.getVersionName(context);
        long time = System.currentTimeMillis();
        String key = AppUtil.getKey(appId + versionName + time);
        OkGo.<String>get(API.getAppInfo).tag(this)
                .params("key", key)
                .params("app_id", appId)
                .params("time", time)

                .execute(new NormalCallBack(application) {
                    @Override
                    public void onSuccessUI(DResponse response, Call call) {
                        if (response.isSuccess()) {
                            JSONObject dataJo = response.getData();
                            String hisavana_appid = JSONUtil.getString(dataJo, "hisavana_appid");
                            JSONArray adJsa = JSONUtil.getJSONArray(dataJo, "adList");
                            if (adJsa == null || adJsa.length() == 0) {
                                LogUtils.e("shufei", "接口返回数据为空");
                                return;
                            }
                            SharedPreferencesUtils.put(application, "adData", adJsa.toString());
                            TAdManager.init(application, new TAdManager.AdConfigBuilder()
                                    .setAppId(hisavana_appid)
                                    .setDebug(isDebug)
                                    .testDevice(isTestDevice)
                                    .build());
                            if(onCallBack!=null){
                                onCallBack.callBack(true);
                            }
                        } else {
                            LogUtils.e("shufei", "初始化失败，接口返回失败");
                            if(onCallBack!=null){
                                onCallBack.callBack(false);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.e("shufei", "初始化失败，网络异常");
                        if(onCallBack!=null){
                            onCallBack.callBack(false);
                        }
                    }

                    @Override
                    public void onErray() {
                        super.onErray();
                        LogUtils.e("shufei", "初始化失败，网络异常");
                        if(onCallBack!=null){
                            onCallBack.callBack(false);
                        }
                    }
                });

    }

    public String getSlotId(String key) {
        String adJsaStr = (String) SharedPreferencesUtils.get(context, "adData", "");
        if (TextUtils.isEmpty(adJsaStr)) {
            LogUtils.e("shufei", "平台未配置对应的广告");
            return "";
        }
        try {
            JSONArray adJsa = new JSONArray(adJsaStr);
            for (int i = 0; i < adJsa.length(); i++) {
                JSONObject itemJo = JSONUtil.getJSONObjectAt(adJsa, i);
                if (itemJo.has(key)) {
                    return JSONUtil.getString(itemJo, key);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtils.e("shufei", "该广告位不存在");
        return "";
    }


    public void recordLog(String ad_log_id, String ad_space_id, String status, OnRecordCallBack onRecordCallBack) {
        String versionName = AppUtil.getVersionName(context);
        long time = System.currentTimeMillis();
        String key = AppUtil.getKey(originalAppId + versionName + time + ad_space_id + ad_log_id + status);
        OkGo.<String>post(API.saveRecord).tag(this)
                .params("ad_log_id", ad_log_id)
                .params("ad_space_id", ad_space_id)
                .params("status", status)
                .params("key", key)
                .params("app_id", originalAppId)
                .params("time", time)

                .execute(new NormalCallBack(AppApplication.mContext) {
                    @Override
                    public void onSuccessUI(DResponse response, Call call) {
                        if (response.isSuccess()) {
                            JSONObject jo = response.getData();

                            String ad_log_id = JSONUtil.getString(jo, "ad_log_id");
                            if (onRecordCallBack != null) {
                                onRecordCallBack.onCallBack(ad_log_id);
                            }

                        }
                    }
                });
    }

    public interface OnRecordCallBack {
        void onCallBack(String adLogId);
    }


    private void initNet(Application context) {


        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(new LoggerInterceptor("person", true));                                 //添加OkGo默认debug日志
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());

        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

        //自动管理cookie（或者叫session的保持），以下几种任选其一就行
        //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(context)));              //使用数据库保持cookie，如果cookie不过期，则一直有效
        //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie，app退出后，cookie消失


        // 其他统一的配置
        // 详细说明看GitHub文档：https://github.com/jeasonlzy/
        OkGo.getInstance().init(context)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(0);                         //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
//                .addCommonHeaders(headers)                      //全局公共头
//                .addCommonParams(params);                       //全局公共参数

    }

    private void initFileProvider() {
        // 解决7.0以上版本的FileProvider问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
    }

    public OnCallBack getOnCallBack() {
        return onCallBack;
    }

    public void setOnCallBack(OnCallBack onCallBack) {
        this.onCallBack = onCallBack;
    }

    public  interface  OnCallBack{
        void  callBack(boolean  isSuccess);
    }

}
